﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using GSQ.BusinessEntities;
using GSQ.BusinessLogic;

namespace UIapp.Dialogos
{
    public partial class frmProductos : Plantillas.frmDialogPlantilla, Interfaces.IPantalla
    {
        public frmProductos(PRODUCTOS entity)
        {
            InitializeComponent();
            try
            {
                if (entity == null)
                {
                    this.newEntity = new PRODUCTOS();
                    this.oldEntity = null;
                }
                else
                {
                    this.oldEntity = entity;
                    this.newEntity = new ProductosBL().GetById(entity.ID);
                }
                this.BindControls();
            }
            catch (Exception ex)
            {
                Comun.ShowMessage(ex);
            }
        }

        #region Variables
        public PRODUCTOS oldEntity;
        public PRODUCTOS newEntity;
        bool entityError = false;
        #endregion

        #region Implementacion IPantalla
        public int ComandosSoportados
        {
            get { return 0; }
        }

        public void Nuevo()
        {
            throw new NotImplementedException();
        }

        public void Modificar()
        {
            throw new NotImplementedException();
        }

        public void Eliminar()
        {
            throw new NotImplementedException();
        }

        public void Refrescar()
        {
            throw new NotImplementedException();
        }

        public void Buscar()
        {
            throw new NotImplementedException();
        }

        public void AgregarProducto(Controles.TransferEntity tranferEntity)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region Metodos auxiliares
        public void BindControls()
        {
            this.txtId.DataBindings.Add("Text", this.newEntity, "ID");
            this.txtCodigo.DataBindings.Add("Text", this.newEntity, "CODIGO");
            if (this.newEntity.ORIGINALES != null)
            {
                this.txtNroOriginal.Text = this.newEntity.ORIGINALES.NRO_ORIGINAL;
            }
            if (this.newEntity.DESCRIPCIONES != null)
            {
                this.txtIdDescripcion.Text = this.newEntity.DESCRIPCIONES.ID.ToString();
                this.txtDescripcion.Text = this.newEntity.DESCRIPCIONES.DESCRIPCION;
            }
            if (this.newEntity.CATEGORIAS != null)
            {
                this.txtIdCategoria.Text = this.newEntity.CATEGORIAS.ID.ToString();
                this.txtCategoria.Text = this.newEntity.CATEGORIAS.CATEGORIA;
            }

            if (this.newEntity.MARCAS != null)
            {
                this.txtIdMarca.Text = this.newEntity.ID_MARCA.ToString();
                this.txtMarca.Text = this.newEntity.MARCAS.MARCA;
            }
            if (this.newEntity.MEDIDAS != null)
            {
                this.txtIdMedida.Text = this.newEntity.ID_MEDIDA.ToString();
                this.txtMedida.Text = this.newEntity.MEDIDAS.MEDIDA;
            }
            this.chkActivo.DataBindings.Add("Checked", this.newEntity, "ACTIVO");

            Binding bindingCosto = new Binding("Text", this.newEntity, "COSTO", true, DataSourceUpdateMode.OnValidation, null, "N2");
            this.txtCosto.DataBindings.Add(bindingCosto);

            Binding bindingPrecio = new Binding("Text", this.newEntity, "PRECIO", true, DataSourceUpdateMode.OnValidation, null, "N2");
            this.txtPrecio.DataBindings.Add(bindingPrecio);

            Binding bindingXGanancia = new Binding("Text", this.newEntity, "X_GANANCIA", true, DataSourceUpdateMode.OnValidation, null, "N4");
            this.txtXGanancia.DataBindings.Add(bindingXGanancia);

            this.chkImpuestos.DataBindings.Add("Checked", this.newEntity, "IMPUESTOS");
            this.chkDescuento.DataBindings.Add("Checked", this.newEntity, "DESCUENTO");

            this.txtUbicacion.DataBindings.Add("Text", this.newEntity, "UBICACION");

            Binding bindingMaximo = new Binding("Text", this.newEntity, "MAXIMO", true, DataSourceUpdateMode.OnValidation, null, "N2");
            this.txtMaximo.DataBindings.Add(bindingMaximo);

            Binding bindingMinimo = new Binding("Text", this.newEntity, "MINIMO", true, DataSourceUpdateMode.OnValidation, null, "N2");
            this.txtMinimo.DataBindings.Add(bindingMinimo);

            Binding bindingExistencia = new Binding("Text", this.newEntity, "EXISTENCIA", true, DataSourceUpdateMode.OnValidation, null, "N2");
            this.txtExistencia.DataBindings.Add(bindingExistencia);
        }

        private void Guardar()
        {
            if (newEntity.IsValid())
            {
                if (this.oldEntity == null)
                {
                    this.newEntity.ACTIVO = true;
                    new ProductosBL().Insert(this.newEntity);
                }
                else
                {
                    new ProductosBL().Update(this.newEntity, this.oldEntity);
                    this.oldEntity = this.newEntity;
                }
                this.entityError = false;
            }
            else
            {
                this.entityError = true;
                Comun.ShowMessage(newEntity);
            }
        }

        private bool BuscarMarca()
        {
            decimal id = 0;
            MARCAS marcas;
            if (decimal.TryParse(this.txtIdMarca.Text.Trim(), out id))
            {
                if (this.newEntity.ID_MARCA == 0 || this.newEntity.ID_MARCA != id)
                {
                    marcas = new MarcasBL().GetById(id);
                    if (marcas != null && marcas.ACTIVO)
                    {
                        this.newEntity.ID_MARCA = marcas.ID;
                        this.txtMarca.Text = marcas.MARCA;
                        this.newEntity.MARCAS = marcas;
                        return true;
                    }
                    else
                    {
                        Comun.ShowInMainMessage("No existen datos con este código");
                        this.newEntity.ID_MARCA = 0;
                        this.newEntity.MARCAS = null;
                        this.txtMarca.Text = "";
                        this.txtIdMarca.Focus();
                        return false;
                    }
                }
                return true;
            }
            this.newEntity.ID_MARCA = 0;
            this.newEntity.MARCAS = null;
            this.txtMarca.Text = "";
            this.txtIdMarca.Focus();
            Comun.ShowInMainMessage("Solo números son permitidos en este campo");
            return false;
        }

        private bool BuscarMedida()
        {
            decimal id = 0;
            MEDIDAS medidas;
            if (decimal.TryParse(this.txtIdMedida.Text.Trim(), out id))
            {
                if (this.newEntity.ID_MEDIDA == 0 || this.newEntity.ID_MEDIDA != id)
                {
                    medidas = new MedidasBL().GetById(id);
                    if (medidas != null && medidas.ACTIVO)
                    {
                        this.newEntity.ID_MEDIDA = medidas.ID;
                        this.txtMedida.Text = medidas.MEDIDA;
                        this.newEntity.MEDIDAS = medidas;
                        return true;
                    }
                    else
                    {
                        Comun.ShowInMainMessage("No existen datos con este código");
                        this.newEntity.ID_MEDIDA = 0;
                        this.newEntity.MEDIDAS = null;
                        this.txtMedida.Text = "";
                        this.txtIdMedida.Focus();
                        return false;
                    }
                }
                return true;
            }
            this.newEntity.ID_MEDIDA = 0;
            this.newEntity.MEDIDAS = null;
            Comun.ShowInMainMessage("Solo números son permitidos en este campo");
            return false;
        }
        #endregion

        #region Tratamiento de eventos
        private void btnAceptar_Click(object sender, EventArgs e)
        {
            try
            {
                this.backgroundWorker.RunWorkerAsync();
                Comun.ShowLoadingFRM();
            }
            catch (Exception ex)
            {
                Comun.ShowMessage(ex);
            }
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Guardar();
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Comun.CloseLoadingFRM();
            if (e.Error != null)
                Comun.ShowMessage(e.Error);
            else if (this.entityError)
                return;
            else
            {
                Comun.ShowInMainMessage("Datos guardados correctamente...");
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
        }

        private void txtIdMarcas_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                if (this.txtIdMarca.Text.Length > 0)
                {
                    if (!this.BuscarMarca())
                    {
                        this.txtMarca.Text = "";
                        this.txtIdMarca.Focus();
                        this.newEntity.MARCAS = null;
                    }
                }
                else
                {
                    this.newEntity.ID_MARCA = 0;
                    this.newEntity.MARCAS = null;
                    this.txtMarca.Text = "";
                }
            }
            catch (Exception ex)
            {
                Comun.ShowMessage(ex);
            }
        }

        private void txtIdMarcas_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.F9)
            {
                Busquedas.frmCatalogos frm = new Busquedas.frmCatalogos(Comun.Catalogos.Marcas);
                frm.ShowDialog();
                if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    this.newEntity.ID_MARCA = ((MARCAS)frm.radGridView.CurrentRow.DataBoundItem).ID;
                    this.newEntity.MARCAS = ((MARCAS)frm.radGridView.CurrentRow.DataBoundItem);
                    this.txtIdMarca.Text = ((MARCAS)frm.radGridView.CurrentRow.DataBoundItem).ID.ToString();
                    this.txtMarca.Text = ((MARCAS)frm.radGridView.CurrentRow.DataBoundItem).MARCA;
                }
            }
        }

        private void txtIdMedidas_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                if (this.txtIdMedida.Text.Length > 0)
                {
                    if (!this.BuscarMedida())
                    {
                        this.txtMedida.Text = "";
                        this.txtIdMedida.Focus();
                        this.newEntity.MARCAS = null;
                    }
                }
                else
                {
                    this.newEntity.ID_MEDIDA = 0;
                    this.txtMedida.Text = "";
                }
            }
            catch (Exception ex)
            {
                Comun.ShowMessage(ex);
            }
        }

        private void txtIdMedidas_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.F9)
            {
                Busquedas.frmCatalogos frm = new Busquedas.frmCatalogos(Comun.Catalogos.Medidas);
                frm.ShowDialog();
                if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    this.newEntity.ID_MEDIDA = ((MEDIDAS)frm.radGridView.CurrentRow.DataBoundItem).ID;
                    this.newEntity.MEDIDAS = ((MEDIDAS)frm.radGridView.CurrentRow.DataBoundItem);
                    this.txtIdMedida.Text = ((MEDIDAS)frm.radGridView.CurrentRow.DataBoundItem).ID.ToString();
                    this.txtMedida.Text = ((MEDIDAS)frm.radGridView.CurrentRow.DataBoundItem).MEDIDA;
                }
            }
        }

        private void txtNroOriginal_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                if (this.txtNroOriginal.Text.Trim() != string.Empty)
                {
                    if (this.newEntity.ORIGINALES == null ||
                        this.newEntity.ORIGINALES.NRO_ORIGINAL == string.Empty ||
                       this.newEntity.ORIGINALES.NRO_ORIGINAL != this.txtNroOriginal.Text.Trim())
                    {
                        ORIGINALES original = new OriginalesBL().GetByNroOriginal(this.txtNroOriginal.Text.Trim());
                        if (original != null)
                        {
                            this.txtNroOriginal.Text = original.NRO_ORIGINAL;
                            this.newEntity.ID_ORIGINAL = original.ID;
                            this.txtIdCategoria.Text = original.ID_CATEGORIA.ToString();
                            this.txtCategoria.Text = original.CATEGORIAS.CATEGORIA;
                            this.newEntity.CATEGORIAS = original.CATEGORIAS;
                            this.txtIdDescripcion.Text = original.ID_DESCRIPCION.ToString();
                            this.txtDescripcion.Text = original.DESCRIPCIONES.DESCRIPCION;
                            this.newEntity.DESCRIPCIONES = original.DESCRIPCIONES;
                            this.newEntity.ORIGINALES = original;
                        }

                        else
                        {
                            Comun.ShowInMainMessage("No existen datos con este código");
                            this.txtNroOriginal.Focus();

                            this.txtIdCategoria.Text = "";
                            this.txtCategoria.Text = "";

                            this.txtIdDescripcion.Text = "";
                            this.txtDescripcion.Text = "";
                            this.newEntity.ORIGINALES = null;
                        }
                    }
                }
                else
                {

                    this.newEntity.CATEGORIAS = null;
                    this.txtIdCategoria.Text = "";
                    this.txtCategoria.Text = "";


                    this.newEntity.DESCRIPCIONES = null;
                    this.txtIdDescripcion.Text = "";
                    this.txtDescripcion.Text = "";

                    this.newEntity.ID_ORIGINAL = 0;
                    this.newEntity.ORIGINALES = null;
                }
            }
            catch (Exception ex)
            {
                Comun.ShowMessage(ex);
            }
        }

        private void frmProductos_Load(object sender, EventArgs e)
        {
            this.chkActivo.Checked = true;
            this.chkDescuento.Checked = true;
            this.chkImpuestos.Checked = true;
        }

        private void txtNroOriginal_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.F9)
            {
                e.Handled = true;
                Vistas.frmOriginales frm = new Vistas.frmOriginales(false);
                frm.ShowDialog();
                if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    this.txtNroOriginal.Text = ((ORIGINALES)frm.radGridView.CurrentRow.DataBoundItem).NRO_ORIGINAL;

                }
            }
        }
        #endregion
    }
}
